import android.content.ContentUris
import android.content.Context
import android.provider.MediaStore
import android.util.Log
import com.cszy.yydqbfq.bean.AudioItemBean
import java.io.File

class AudioLoadRepository(private val context: Context) {

    fun loadAudioFiles(): List<AudioItemBean> {
        val audioMap = mutableMapOf<String, AudioItemBean>() // 用Map去重，key为文件路径

        val projection = arrayOf(
            MediaStore.Audio.Media._ID,
            MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.ARTIST,
            MediaStore.Audio.Media.DURATION,
            MediaStore.Audio.Media.SIZE,
            MediaStore.Audio.Media.DATA
        )

        val selection = "${MediaStore.Audio.Media.DURATION} > 0"

        context.contentResolver.query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            projection,
            selection,
            null,
            "${MediaStore.Audio.Media.DATE_ADDED} DESC"
        )?.use { cursor ->
            val idCol = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)
            val titleCol = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)
            val artistCol = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)
            val durationCol = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)
            val sizeCol = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE)
            val dataCol = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)

            while (cursor.moveToNext()) {
                val path = cursor.getString(dataCol) ?: continue
                if (isValidAudioFile(path)) {
                    val id = cursor.getLong(idCol)
                    val audioItem = AudioItemBean(
                        id = id,
                        title = cursor.getString(titleCol) ?: "未知标题",
                        artist = cursor.getString(artistCol) ?: "未知艺术家",
                        duration = cursor.getLong(durationCol),
                        size = cursor.getLong(sizeCol),
                        path = path,
                        uriString = ContentUris.withAppendedId(
                            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                            id
                        ).toString()
                    )
                    // 使用文件路径作为key去重
                    audioMap[path] = audioItem
                }
            }
        }

        Log.d("AudioQuery", "Found ${audioMap.size} unique audio files")
        return audioMap.values.toList()
    }

    private fun isValidAudioFile(path: String): Boolean {
        val file = File(path)
        return file.exists() &&
                !path.contains("/Android/") &&
                !path.contains("/.") &&
                path.let {
                    it.endsWith(".mp3", true) ||
                            it.endsWith(".flac", true) ||
                            it.endsWith(".wav", true) ||
                            it.endsWith(".m4a", true)
                }
    }
}